// packageA/pages/dislist/index.js
Page({

    /**
     * 页面的初始数据
     */
    data: {
        // 搜索和筛选条件
        searchPhone: '',
        timeFilter: 'all', // all, today, week, month
        sortBy: 'amount', // amount, time
        sortOrder: 'desc', // asc, desc
        filterStatus: 'all', // all, approved, pending

        // 数据看板
        dashboard: {
            storeCount: 0,
            userCount: 0,
            orderCount: 0,
            totalAmount: 0,
            withdrawnAmount: 0,
            pendingAmount: 0
        },

        // 分店列表数据
        stores: [],
        filteredStores: []
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        // 加载数据
        this.loadDashboardData();
        this.loadStoreList();
    },
    // 加载数据看板数据
    loadDashboardData: function () {
        // 模拟API调用
        setTimeout(() => {
            this.setData({
                dashboard: {
                    storeCount: 156,
                    userCount: 3420,
                    orderCount: 12890,
                    totalAmount: 258900.50,
                    withdrawnAmount: 125600.00,
                    pendingAmount: 133300.50
                }
            });
        }, 500);
    },

    // 加载分店列表
    loadStoreList: function (callback) {
        // 模拟API调用
        setTimeout(() => {
            const stores = [
                {
                    id: 'S1001',
                    name: '鲜果时光水果店',
                    phone: '138****1234',
                    userCount: 156,
                    orderAmount: 25890.50,
                    commission: 5178.10,
                    withdrawnAmount: 4000.00,
                    pendingAmount: 1178.10,
                    withdrawalCount: 3,
                    status: 'approved',
                    createTime: '2023-05-15'
                },
                {
                    id: 'S1002',
                    name: '便利生活超市',
                    phone: '139****5678',
                    userCount: 89,
                    orderAmount: 14230.00,
                    commission: 2846.00,
                    withdrawnAmount: 2000.00,
                    pendingAmount: 846.00,
                    withdrawalCount: 2,
                    status: 'approved',
                    createTime: '2023-06-20'
                },
                {
                    id: 'S1003',
                    name: '天天鲜果',
                    phone: '137****9012',
                    userCount: 45,
                    orderAmount: 7890.00,
                    commission: 1578.00,
                    withdrawnAmount: 1000.00,
                    pendingAmount: 578.00,
                    withdrawalCount: 1,
                    status: 'pending',
                    createTime: '2023-07-10'
                },
                {
                    id: 'S1004',
                    name: '社区便民店',
                    phone: '136****3456',
                    userCount: 120,
                    orderAmount: 19870.00,
                    commission: 3974.00,
                    withdrawnAmount: 3000.00,
                    pendingAmount: 974.00,
                    withdrawalCount: 2,
                    status: 'approved',
                    createTime: '2023-06-05'
                },
                {
                    id: 'S1005',
                    name: '果缤纷',
                    phone: '135****7890',
                    userCount: 67,
                    orderAmount: 11250.00,
                    commission: 2250.00,
                    withdrawnAmount: 1500.00,
                    pendingAmount: 750.00,
                    withdrawalCount: 1,
                    status: 'pending',
                    createTime: '2023-07-15'
                }
            ];

            this.setData({
                stores: stores,
                filteredStores: this.filterStores(stores)
            });

            if (callback) callback();
        }, 800);
    },

    // 搜索输入处理
    onSearchInput: function (e) {
        this.setData({
            searchPhone: e.detail.value
        });
        this.applyFilters();
    },

    // 执行搜索
    onSearch: function () {
        this.applyFilters();
    },

    // 时间筛选
    onTimeFilter: function (e) {
        const filter = e.currentTarget.dataset.filter;
        this.setData({
            timeFilter: filter
        });
        this.applyFilters();
    },

    // 按金额排序
    onSortByAmount: function () {
        const newOrder = this.data.sortOrder === 'asc' ? 'desc' : 'asc';
        this.setData({
            sortBy: 'amount',
            sortOrder: newOrder
        });
        this.applyFilters();
    },

    // 状态筛选
    onFilterStatus: function (e) {
        const status = e.currentTarget.dataset.status;
        this.setData({
            filterStatus: status
        });
        this.applyFilters();
    },

    // 应用所有筛选条件
    applyFilters: function () {
        const { stores, searchPhone, timeFilter, sortBy, sortOrder, filterStatus } = this.data;
        let filtered = [...stores];

        // 按联系方式筛选
        if (searchPhone) {
            filtered = filtered.filter(store =>
                store.phone.includes(searchPhone.replace(/\*/g, ''))
            );
        }

        // 按时间筛选
        if (timeFilter !== 'all') {
            const now = new Date();
            let startDate;

            switch (timeFilter) {
                case 'today':
                    startDate = new Date(now.getFullYear(), now.getMonth(), now.getDate());
                    break;
                case 'week':
                    startDate = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
                    break;
                case 'month':
                    startDate = new Date(now.getFullYear(), now.getMonth(), 1);
                    break;
            }

            filtered = filtered.filter(store => {
                const createDate = new Date(store.createTime);
                return createDate >= startDate;
            });
        }

        // 按状态筛选
        if (filterStatus !== 'all') {
            filtered = filtered.filter(store => store.status === filterStatus);
        }

        // 排序
        filtered.sort((a, b) => {
            if (sortBy === 'amount') {
                return sortOrder === 'asc' ?
                    a.orderAmount - b.orderAmount :
                    b.orderAmount - a.orderAmount;
            }
            return 0;
        });

        this.setData({
            filteredStores: filtered
        });
    },

    // 删除分店
    onDeleteStore: function (e) {
        const storeId = e.currentTarget.dataset.id;
        const storeName = this.data.stores.find(s => s.id === storeId).name;

        wx.showModal({
            title: '确认删除',
            content: `确定要删除分店"${storeName}"吗？此操作不可恢复。`,
            confirmColor: '#f44336',
            success: (res) => {
                if (res.confirm) {
                    // 模拟API调用删除
                    wx.showLoading({
                        title: '删除中...',
                    });

                    setTimeout(() => {
                        const stores = this.data.stores.filter(store => store.id !== storeId);
                        this.setData({
                            stores: stores,
                            filteredStores: this.filterStores(stores)
                        });

                        wx.hideLoading();
                        wx.showToast({
                            title: '删除成功',
                            icon: 'success'
                        });

                        // 更新数据看板
                        this.loadDashboardData();
                    }, 1000);
                }
            }
        });
    },

    // 审核通过分店
    onApproveStore: function (e) {
        const storeId = e.currentTarget.dataset.id;
        const storeName = this.data.stores.find(s => s.id === storeId).name;

        wx.showModal({
            title: '审核通过',
            content: `确定要通过分店"${storeName}"的审核吗？`,
            confirmColor: '#4caf50',
            success: (res) => {
                if (res.confirm) {
                    // 模拟API调用审核通过
                    wx.showLoading({
                        title: '处理中...',
                    });

                    setTimeout(() => {
                        const stores = this.data.stores.map(store => {
                            if (store.id === storeId) {
                                return { ...store, status: 'approved' };
                            }
                            return store;
                        });

                        this.setData({
                            stores: stores,
                            filteredStores: this.filterStores(stores)
                        });

                        wx.hideLoading();
                        wx.showToast({
                            title: '审核通过',
                            icon: 'success'
                        });
                    }, 800);
                }
            }
        });
    },

    // 驳回分店（将状态改为审核中）
    onRejectStore: function (e) {
        const storeId = e.currentTarget.dataset.id;
        const storeName = this.data.stores.find(s => s.id === storeId).name;

        wx.showModal({
            title: '驳回申请',
            content: `确定要将分店"${storeName}"状态改为审核中吗？`,
            confirmColor: '#ff9800',
            success: (res) => {
                if (res.confirm) {
                    // 模拟API调用驳回
                    wx.showLoading({
                        title: '处理中...',
                    });

                    setTimeout(() => {
                        const stores = this.data.stores.map(store => {
                            if (store.id === storeId) {
                                return { ...store, status: 'pending' };
                            }
                            return store;
                        });

                        this.setData({
                            stores: stores,
                            filteredStores: this.filterStores(stores)
                        });

                        wx.hideLoading();
                        wx.showToast({
                            title: '已驳回',
                            icon: 'success'
                        });
                    }, 800);
                }
            }
        });
    },

    // 辅助函数：应用当前筛选条件
    filterStores: function (stores) {
        const { searchPhone, timeFilter, filterStatus } = this.data;
        let filtered = [...stores];

        // 按联系方式筛选
        if (searchPhone) {
            filtered = filtered.filter(store =>
                store.phone.includes(searchPhone.replace(/\*/g, ''))
            );
        }

        // 按时间筛选
        if (timeFilter !== 'all') {
            const now = new Date();
            let startDate;

            switch (timeFilter) {
                case 'today':
                    startDate = new Date(now.getFullYear(), now.getMonth(), now.getDate());
                    break;
                case 'week':
                    startDate = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
                    break;
                case 'month':
                    startDate = new Date(now.getFullYear(), now.getMonth(), 1);
                    break;
            }

            filtered = filtered.filter(store => {
                const createDate = new Date(store.createTime);
                return createDate >= startDate;
            });
        }

        // 按状态筛选
        if (filterStatus !== 'all') {
            filtered = filtered.filter(store => store.status === filterStatus);
        }

        return filtered;
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {
        // 下拉刷新
        this.loadDashboardData();
        this.loadStoreList(() => {
            wx.stopPullDownRefresh();
        });
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})